package com.renwei.yunlong.activity.work;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.renwei.yunlong.R;
import com.renwei.yunlong.base.BaseActivity;
import com.renwei.yunlong.bean.BridgeTitleBean;
import com.renwei.yunlong.bean.FinishAllPagerBean;
import com.renwei.yunlong.bean.FinshPagerBean;
import com.renwei.yunlong.bean.GuideInfo;
import com.renwei.yunlong.http.Api;
import com.renwei.yunlong.utils.CommonUtils;
import com.renwei.yunlong.utils.DialogUtils;
import com.renwei.yunlong.utils.JsonMapUtil;
import com.renwei.yunlong.utils.ServiceRequestManager;
import com.renwei.yunlong.utils.StringUtils;
import com.tencent.smtt.export.external.interfaces.SslError;
import com.tencent.smtt.export.external.interfaces.SslErrorHandler;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.zyf.fwms.commonlibrary.utils.StatusBarUtil;

import java.util.HashMap;

import butterknife.ButterKnife;
import github.benjamin.tbsreader.bridge.BridgeHandler;
import github.benjamin.tbsreader.bridge.CallBackFunction;
import github.benjamin.tbsreader.bridge.DefaultHandler;
import github.benjamin.tbsreader.bridge.SimpleBridgeWebViewClientListener;
import github.benjamin.tbsreader.bridge.TbsBridgeWebView;


/**
 * Created by wangqi on 2018/1/23.
 */

public class GuideWebActivity extends BaseActivity implements View.OnClickListener {
    private String TAG = "WebBrowserActivity";
    TbsBridgeWebView webView;
    GuideInfo guideInfo;
    private ImageView ivBack;
    private TextView tvTitle;
    private ImageView ivRight;
    private RelativeLayout topBar;
    private FinshPagerBean finshPagerBean;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_guide_web);
        ButterKnife.bind(this);
        getWindow().setFormat(PixelFormat.TRANSLUCENT);
        StatusBarUtil.setColor(this, CommonUtils.getColor(this, R.color.color_web_bg), 0);
        guideInfo = (GuideInfo) getIntent().getSerializableExtra("guide");
        initView();
    }

    private void initView() {
        ivBack = findViewById(R.id.iv_back);
        ivBack.setOnClickListener(this);
        tvTitle = findViewById(R.id.tv_title);
        ivRight = findViewById(R.id.iv_right);
        ivRight.setOnClickListener(this);
        topBar = findViewById(R.id.top_bar);
        topBar.setBackgroundColor(Color.parseColor("#474F61"));
        ivBack.setImageResource(R.mipmap.guide);
        webView = findViewById(github.benjamin.tbsreader.R.id.webView);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setSaveFormData(false);
        webView.getSettings().setSavePassword(false);
        webView.getSettings().setSupportZoom(true);
        webView.getSettings().setDomStorageEnabled(true);
        webView.getSettings().setBuiltInZoomControls(true);
        webView.getSettings().setDisplayZoomControls(false);
        webView.getSettings().setLoadWithOverviewMode(true);
        //设定支持h5viewport
        webView.getSettings().setUseWideViewPort(true);
        // 自适应屏幕.
        webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webView.setBridgeWebViewClientListener(new SimpleBridgeWebViewClientListener());
        //=======================此方法必须调用==========================
        webView.setDefaultHandler(new DefaultHandler());
        //=======================js桥使用改方法替换原有setWebViewClient()方法==========================
        webView.setBridgeWebViewClientListener(new SimpleBridgeWebViewClientListener() {

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Log.i(TAG, "超链接：" + url);
                return false;
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap bitmap) {

            }

            @Override
            public void onPageFinished(WebView view, String url) {

            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {

            }

            @Override
            public boolean onReceivedSslError(WebView webView, final SslErrorHandler sslErrorHandler, SslError sslError) {
                /*String message;
                switch (sslError.getPrimaryError()) {
                    case android.net.http.SslError.SSL_UNTRUSTED:
                        message = "证书颁发机构不受信任";
                        break;
                    case android.net.http.SslError.SSL_EXPIRED:
                        message = "证书过期";
                        break;
                    case android.net.http.SslError.SSL_IDMISMATCH:
                        message = "网站名称与证书不一致";
                        break;
                    case android.net.http.SslError.SSL_NOTYETVALID:
                        message = "证书无效";
                        break;
                    case android.net.http.SslError.SSL_DATE_INVALID:
                        message = "证书日期无效";
                        break;
                    case android.net.http.SslError.SSL_INVALID:
                    default:
                        message = "证书错误";
                        break;
                }
                AlertDialog.Builder builder = new AlertDialog.Builder(GuideWebActivity.this);
                builder.setTitle("提示").setMessage(message + "，是否继续").setCancelable(true)
                        .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int id) {
                                sslErrorHandler.proceed();
                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int id) {
                                sslErrorHandler.cancel();
                            }
                        });
                AlertDialog alert = builder.create();
                alert.show();*/
                sslErrorHandler.proceed();
                return true;
            }
        });
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
            }

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
            }
        });
        String url;
        if (guideInfo == null) {
            url = getIntent().getStringExtra("url");

        } else {
            url = Api.$().GuideUri + StringUtils.value(guideInfo.getModelUrl());
        }
        webView.loadUrl(url);
        webView.setCustom("TestJavascriptBridge");
        webView.registerHandler("initSignNetShare", new BridgeHandler() {

            @Override
            public void handler(String data, CallBackFunction function) {
                Log.i(TAG, "回传结果：" + data);
                Toast.makeText(GuideWebActivity.this, data, Toast.LENGTH_SHORT).show();
            }
        });

        //=======================以下4个web调用native示例方法==========================
        webView.registerHandler("initSignNetPay", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                Log.i(TAG, "回传结果：" + data);
                Toast.makeText(GuideWebActivity.this, data, Toast.LENGTH_SHORT).show();
            }
        });
        /**
         * 打开页面标题
         */
        webView.registerHandler("startPager", new BridgeHandler() {

            @Override
            public void handler(String data, CallBackFunction function) {
                BridgeTitleBean titleBean = new Gson().fromJson(data, BridgeTitleBean.class);
                String title = StringUtils.value(titleBean.getTitle() + "(" + titleBean.getCurrent() + "/" + titleBean.getTotal() + "" + ")");
                tvTitle.setText(title);
            }
        });
        /**
         * 打开页面标题
         */
        webView.registerHandler("finishCurrentPager", new BridgeHandler() {

            @Override
            public void handler(String data, CallBackFunction function) {
                finshPagerBean = new Gson().fromJson(data, FinshPagerBean.class);
                uploadCheckGuide(finshPagerBean.getCurrentTag());
                /*case "学习发起工单":
                case "学习指派工单":
                case "学习接受工单":
                case "学习处理工单":
                case "学习确认工单":
                case "通过企业认证":
                case "邀请好友企业":
                case "添加工作人员":
                case "对象是什么":
                case "备件是什么":
                case "什么是项目":
                case "什么是服务目录":
                case "什么是SLA模板":*/
            }
        });
    }

    private void uploadCheckGuide(String code) {
        HashMap<String, String> map = new HashMap();
        map.put("modelName", StringUtils.value(code));
        if ("1".equals(companyType)) {
            map.put("userName", ownerBean.getRows().getUserName());
        } else if ("2".equals(companyType)) {
            map.put("userName", serviceLoginBean.getRows().getUserName());
        }
        ServiceRequestManager.getManager().uploadGuideCheck(this, JsonMapUtil.mapToJson(map), this);
    }


    @Override
    public void onSuccess(int requestId, String result) {
        switch (requestId) {
            case 889:
                FinishAllPagerBean bean = new Gson().fromJson(result, FinishAllPagerBean.class);
                if (bean.getMessage() != null && bean.getMessage().getCode() == 200 && "0".equals(bean.getRows())) {
                    String arry[] = new String[3];
                    arry[0] = StringUtils.value(finshPagerBean.getTitle1());
                    arry[1] = StringUtils.value(finshPagerBean.getTitle2());
                    arry[2] = StringUtils.value(finshPagerBean.getMessage());
                    showGuidView(arry);
                } else if (bean.getMessage() != null && bean.getMessage().getCode() == 200 && "1".equals(bean.getRows()) && guideInfo != null) {
                    showFinishGuidView();
                } else {
                    String arry[] = new String[3];
                    arry[0] = StringUtils.value(finshPagerBean.getTitle1());
                    arry[1] = StringUtils.value(finshPagerBean.getTitle2());
                    arry[2] = StringUtils.value(finshPagerBean.getMessage());
                    showGuidView(arry);
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onException(int requestId, String code) {
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.left_parent:
                showGuidView(new String[0]);
                break;
            case R.id.right_parent:
                GuideListActivity.openActivity(this);
                break;
            case R.id.iv_right:
                finish();
                break;
            default:
                break;
            case R.id.iv_back:
                GuideListActivity.openActivity(this);
                break;
        }
    }

    private void showGuidView(String[] message) {
        DialogUtils.showGuidePop(this, ivBack, R.mipmap.icon_guide_next, message,
                new DialogUtils.OnGuideListener() {
                    @Override
                    public void onButtonClick(PopupWindow popupWindow, Button button) {
                        switch (StringUtils.value(button.getText())) {
                            case "继续引导":
                                GuideListActivity.openActivity(mContext);
                                break;
                            case "不用谢谢":
                                popupWindow.dismiss();
                                break;
                            default:
                                break;

                        }
                    }
                }, "继续引导", " 不用谢谢");
    }

    private void showFinishGuidView() {
        String arry[] = new String[4];
        arry[0] = "太棒了！";
        arry[1] = "恭喜您完成了所有引导";
        arry[2] = "请尽情使用云呐";
        arry[3] = "如有问题可在设置中反馈";
        DialogUtils.showGuidePop(this, ivBack, R.mipmap.icon_guide_end, arry,
                new DialogUtils.OnGuideListener() {
                    @Override
                    public void onButtonClick(PopupWindow popupWindow, Button button) {
                        switch (StringUtils.value(button.getText())) {
                            case "好的":
                                GuideListActivity.openActivity(GuideWebActivity.this);
                                break;
                            default:
                                break;

                        }
                    }
                }, "好的");
    }

    @Override
    public void onBackPressed() {
        if (webView != null) {
            if (webView.canGoBack()) {
                webView.goBack();
            } else {
                finish();
            }
        }
    }

    /**
     * @param context
     * @param url     web URL
     */
    public static void openActivity(Context context, String url) {
        Intent intent = new Intent(context, GuideWebActivity.class);
        intent.putExtra("url", url);
        context.startActivity(intent);
    }

    /**
     * @param context
     * @param info    guide对象
     */
    public static void openActivity(Context context, GuideInfo info) {
        Intent intent = new Intent(context, GuideWebActivity.class);
        intent.putExtra("guide", info);
        context.startActivity(intent);
    }

}
